<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <TreeTools :data="company">
          <el-dropdown-item :disabled="!hasPerm('point-dept')" @click.native="onAdd(company)">添加子部门</el-dropdown-item>
        </TreeTools>
        <el-tree
          :data="list"
          :props="{label:'name'}"
          default-expand-all
          :expand-on-click-node="false"
        >
          <template v-slot="{data}">
            <TreeTools :data="data">
              <el-dropdown-item :disabled="!hasPerm('point-dept')" @click.native="onAdd(data)">添加子部门</el-dropdown-item>
              <el-dropdown-item @click.native="onUpdate(data)">编辑子部门</el-dropdown-item>
              <el-dropdown-item @click.native="onDel(data.id)">删除部门</el-dropdown-item>
            </TreeTools>
          </template>
        </el-tree>
      </el-card>
    </div>
    <AddDept ref="addDeptRef" :node="currentNode" :show-dialog.sync="showDialog" @success="getList" />
  </div>
</template>

<script>
import TreeTools from './components/tree-tools.vue'
import { getDepartmentsAPI, delDepartmentsAPI, updateDepartmentsAPI, getDepartDetailAPI } from '@/api'
import { getChildren } from '@/utils'
import AddDept from './components/add-dept.vue'
export default {
  name: 'DepartmentsPage',
  components: { TreeTools, AddDept },
  data() {
    return {
      currentNode: {}, // 当前操作的部门
      showDialog: false,
      company: { name: '负责人', manager: '羊羊办公室', id: '' },
      list: []
    }
  },
  async created() {
    this.getList()
  },
  mounted() {

  },
  methods: {
    handleNodeClick(data) {
      // console.log(data)
    },
    // 添加
    onAdd(node) {
      this.showDialog = true
      this.currentNode = node
      // console.log(node)
    },
    // 编辑
    async onUpdate(node) {
      console.log(node)
      this.$refs.addDeptRef.form = await getDepartDetailAPI(node.id)
      this.currentNode = node
      this.showDialog = true
    },
    // 删除
    async onDel(id) {
      let loading
      // 删除确认框
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 加载提示
        loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        await delDepartmentsAPI(id)
        this.getList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        loading.close()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '删除失败'
        })
        loading.close()
      })
    },
    // 获取列表数据
    async getList() {
      const { companyName, depts } = await getDepartmentsAPI()
      this.list = getChildren(depts.filter(i => i.pid !== -1), '')
    }

  }
}
</script>

<style scoped>
.tree-card {
  padding: 30px  140px;
  font-size:14px;
}
</style>
